import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/screens/home_screen.dart';
import 'package:wayofdressing/screens/my_screen.dart';
import 'package:wayofdressing/screens/explore_screen.dart';
import 'package:wayofdressing/screens/messages_screen.dart';
import 'package:wayofdressing/category/clothcategory.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'category/outfitcategory.dart';
import 'components/clothbox.dart';
import 'components/clothboxes.dart';
import 'dio/ClothDio.dart';
import 'dio/MessageDio.dart';
import 'dio/OutfitDio.dart';
import 'all_information/message_datas.dart';
import 'package:wayofdressing/good_method/decode_base64_to_bytes.dart';
class MainNavigatorWidget extends StatefulWidget {
  static final String id = 'mainnavigatorwidget';

  @override
  _MainNavigatorWidgetState createState() => _MainNavigatorWidgetState();
}

class _MainNavigatorWidgetState extends State<MainNavigatorWidget>
    with SingleTickerProviderStateMixin {
  List<String> categories = [];
  int _currentIndex = 0;
  int Index = 0;
  var _pageController = PageController(
    initialPage: 0,
  );

  void _fetchLatestMessages() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int userId = prefs.getInt('id')!;
    try {
      Response<dynamic> response = await getLatestMessagesBySenderId(
        userId: userId,
        dio: dio,
      );
      dynamic data = response.data['data'];
      latestMessages.clear();
      for (dynamic item in data) {
        String latestMessage = item['messageText'];
        int receiverId = item['receiver']['id'];
        int senderId=item['sender']['id'];
        String sentAt= item['sentAt'];
        Map<String, dynamic> message;
        if(receiverId!=userId){
          String receiverName = item['receiver']['name'];
          String? base64Image = item['receiver']['userDetailDTO']['imageBytes'];
          dynamic headImage=AssetImage('images/peanut.jpg');
          if (base64Image != null && base64Image.isNotEmpty) {
            Uint8List imageBytes = decodeBase64ToBytes(base64Image);
            headImage=MemoryImage(imageBytes);
          }
          message = {
            'sentAt':sentAt,
            'latestMessage': latestMessage,
            'receiverId': receiverId,
            'receiverName': receiverName,
            'headImage':headImage,
          };
        }
        else{
          String receiverName = item['sender']['name'];
          String? base64Image = item['sender']['userDetailDTO']['imageBytes'];
          dynamic headImage=AssetImage('images/peanut.jpg');
          if (base64Image != null && base64Image.isNotEmpty) {
            Uint8List imageBytes = decodeBase64ToBytes(base64Image);
            headImage=MemoryImage(imageBytes);
          }
          message = {
            'sentAt':sentAt,
            'latestMessage': latestMessage,
            'receiverId': senderId,
            'receiverName': receiverName,
            'headImage':headImage,
          };
        }
        latestMessages.add(message);
      }
      latestMessages.sort((a,b)=>a['sentAt'].compareTo(b['sentAt']));
    } catch (e) {
      // 处理异常情况，例如显示错误消息或者重新尝试获取数据
      print('Error fetching latest messages: $e');
    }
  }

  List<Widget> _createClothBoxes(Response<dynamic> response) {
    List<Widget> clothBoxes = [];
    List<dynamic> data = response.data['data']; // 根据你的 API 响应结构调整

    for (var item in data) {
      // 假设 item 中的 imageBytes 是 Base64 编码的字符串
      String? base64Image = item['imageBytes']; // 获取 Base64 编码的字符串
      Map<String, dynamic> cloth = {
        'userClothId': item['userClothId'] ?? '无',
        'name': item['clothName'] ?? '无',
        'category': item['category'] ?? '无',
        'subcategory': item['subcategory'] ?? '无'
      };
      if (base64Image != null && base64Image.isNotEmpty) {
        try {
          // 解码 Base64 编码的字符串为 Uint8List
          Uint8List imageBytes = decodeBase64ToBytes(base64Image);
          // 使用解码后的图像字节显示图像
          clothBoxes.add(
            ClothBox(
              hasImage: true,
              cloth: cloth,
              childWidget: Image.memory(imageBytes), // 显示图像
            ),
          );
        } catch (error) {
          print('Error decoding or displaying image: $error');
          // 处理图像解码错误的情况，例如使用占位图像
          clothBoxes.add(
            ClothBox(
              hasImage: false,
              cloth: cloth,
              childWidget: Container(
                child: Center(child: Text('没有图片')),
              ), // 占位或默认图像
            ),
          );
        }
      } else {
        // 处理 imageBytes 为 null 或空的情况
        clothBoxes.add(
          ClothBox(
            hasImage: false,
            cloth: cloth,
            childWidget: Container(
              child: Center(child: Text('没有图片')),
            ), // 占位或默认图像
          ),
        );
      }
    }
    return clothBoxes;
  }

  Future<void> _fetchClothData() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int userId = prefs.getInt('id') ?? 0; // Fetch user ID from SharedPreferences
      clothCategoryWidgetList.clear();
      clothSubCategoryWidgetList.clear();

      for (String item in clothCategories) {
        for (String item1 in clothSubCategories[item]!) {
          Response<dynamic> response = await getClothByUserIdAndSubcategory(
            userId: userId,
            subcategory: item1,
            dio: dio,
          );
          setState(() {
            clothSubCategoryWidgetList[item1] = _createClothBoxes(response);
            if (!clothCategoryWidgetList.containsKey(item)) {
              clothCategoryWidgetList[item] = [];
            }
            clothCategoryWidgetList[item]!.add(ClothBoxes(
              clothesName: item1,
              clothes: clothSubCategoryWidgetList[item1]!,
            ));
          });
        }
      }
    } catch (e) {
      print('Error fetching category data: $e');
    }
  }

  Future<void> _getDress() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int userId = prefs.getInt('id') ?? 0;
      for (String item in outfits) {
        Response response = await getOutfitByUserIdAndCategory(
            userId: userId, category: item, dio: dio);
        if (response.data['success'] == true) {
          List<String> names = [];
          List<dynamic> data = response.data['data'];
          outfitInformation[item]?.clear();
          for (dynamic item1 in data) {
            Map<String, dynamic> outfitData = Map<String, dynamic>.from(item1);
            outfitInformation[item]?.add(outfitData);
            names.add(item1['name']);
          }
          outfitNumbers[item] = names;
        } else {
          print('Failed to fetch data for category: $item');
        }
      }
    } catch (e) {
      print('Error fetching category data: $e');
    }
  }

  @override
  void initState() {
    super.initState();
    _fetchClothData();
    _getDress();
    categories = clothSubCategories.keys.toList();
    _fetchLatestMessages();
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }

  Widget buildBodyFunction() {
    return Stack(
      children: <Widget>[
        Opacity(
          opacity: Index == 0 ? 1 : 0,
          child: IgnorePointer(
              ignoring: Index == 0 ? false : true, child: HomeScreen()),
        ),
        Opacity(
          opacity: Index == 1 ? 1 : 0,
          child: IgnorePointer(
              ignoring: Index == 1 ? false : true, child: ExploreScreen()),
        ),
        Opacity(
          opacity: Index == 2 ? 1 : 0,
          child: IgnorePointer(
              ignoring: Index == 2 ? false : true, child: MessagesScreen()),
        ),
        Opacity(
          opacity: Index == 3 ? 1 : 0,
          child: IgnorePointer(
              ignoring: Index == 3 ? false : true, child: MyScreen()),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: buildBodyFunction(),
      bottomNavigationBar: Theme(
        data: ThemeData(
          canvasColor: Color(0xfffffaf0),
        ),
        child: BottomNavigationBar(
          elevation: 0,
          currentIndex: _currentIndex,
          onTap: (index) {
            setState(() {
              _currentIndex = index;
              Index = index;
              if(index ==2){
                _fetchLatestMessages();
              }
            });
          },
          items: datas.map((data) {
            return BottomNavigationBarItem(
              label: '',
              icon: Container(
                margin: EdgeInsets.symmetric(vertical: 4.0, horizontal: 6.0),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25.0),
                    color: Colors.transparent),
                child: Icon(
                  data.icon,
                  size: 35,
                  color: Colors.black,
                ),
              ),
              activeIcon: Container(
                height: 50,
                margin: EdgeInsets.symmetric(vertical: 4.0, horizontal: 6.0),
                decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3), // 阴影颜色和透明度
                      spreadRadius: 2, // 阴影扩展半径
                      blurRadius: 5, // 阴影模糊半径
                      offset: Offset(0, 6), // 阴影偏移量
                    ),
                  ],
                  borderRadius: BorderRadius.circular(25.0),
                  color: Color(0xff0927eb),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      data.icon,
                      size: 35,
                      color: Colors.white,
                    ),
                    Flexible(
                      child: Text(
                        data.title,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

class TabData {
  const TabData({required this.index, required this.title, required this.icon});

  final String title;

  final IconData icon;

  final int index;
}

List<TabData> datas = <TabData>[
  TabData(index: 0, title: '首页', icon: Icons.home_outlined),
  TabData(index: 1, title: '探索', icon: Icons.explore_outlined),
  TabData(index: 2, title: '消息', icon: Icons.messenger_outline_rounded),
  TabData(index: 3, title: '我的', icon: Icons.person_outline_rounded),
];
